<template>
  <div class="doctor-form-container">
    <Main :title="titleText">
      <template #breadcrumb>
        <Breadcrumb>
          <BreadcrumbItem>医生管理</BreadcrumbItem>
          <BreadcrumbItem>{{ actionText }}</BreadcrumbItem>
        </Breadcrumb>
      </template>
    </Main>

    <Card class="form-card">
      <Form :model="form" :rules="rules" ref="formRef" label-width="120">
        <Row>
          <Col span="12">
            <FormItem label="医生姓名*" prop="doctorName">
              <Input v-model="form.doctorName" placeholder="请输入医生姓名" />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="上传照片*" prop="photo">
              <input
                type="file"
                ref="fileInput"
                accept="image/*"
                @change="handleFileChange"
                style="display: none"
              />
              <Button type="ghost" :loading="uploading" @click="triggerUpload">
                <Icon type="ios-cloud-upload" /> {{ tempPhoto ? '更换图片' : '点击上传' }}
              </Button>

              <div class="preview-container">
                <div v-if="tempPhoto" class="preview-image">
                  <img :src="tempPhoto" alt="医生照片" class="preview-img" />
                  <Button type="danger" size="small" class="delete-btn" @click="clearPhoto">
                    删除
                  </Button>
                </div>
                <div v-else class="upload-placeholder">
                  <span>请上传医生照片（JPG/PNG，≤2MB）</span>
                </div>
                <div v-if="uploadError" class="upload-error-message">
                  {{ uploadError }}
                </div>
              </div>
            </FormItem>
          </Col>
        </Row>

        <Row>
          <Col span="12">
            <FormItem label="所属院区*" prop="hospitalArea">
              <Select v-model="form.hospitalArea" placeholder="请选择院区">
                <Option v-for="area in areaOptions" :value="area.value" :key="area.value">
                  {{ area.label }}
                </Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="所属科室*" prop="department">
              <Select v-model="form.department" placeholder="请选择科室">
                <Option v-for="dept in departmentOptions" :value="dept.value" :key="dept.value">
                  {{ dept.label }}
                </Option>
              </Select>
            </FormItem>
          </Col>
        </Row>

        <Row>
          <Col span="12">
            <FormItem label="医生职称*" prop="position">
              <Select v-model="form.position" placeholder="请选择医生职称">
                <Option v-for="pos in positionOptions" :value="pos.value" :key="pos.value">
                  {{ pos.label }}
                </Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="挂号费*" prop="registrationFee">
              <Input v-model.number="form.registrationFee" type="number" placeholder="请输入挂号费" />
            </FormItem>
          </Col>
        </Row>

        <Row>
          <Col span="24">
            <FormItem label="医生简介" prop="introduction">
              <Input type="textarea" v-model="form.introduction" rows="4" placeholder="请输入医生简介" />
            </FormItem>
          </Col>
        </Row>

        <Row>
          <Col span="12">
            <FormItem label="医生状态" prop="status">
              <Switch v-model="form.status" />
              <span class="ml-10">启用/禁用</span>
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Card>

    <div class="form-actions">
      <Button @click="handleCancel">取消</Button>
      <Button type="primary" @click="handleSave">保存</Button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue';
import "../../../mockjs/doctorManagement/doctorMock"
import Main from "@/components/main.vue"
import { useRoute, useRouter } from 'vue-router';
import { fetchDoctorById, saveDoctor } from '@/api/doctorManagmentModal/doctor';

// 类型定义
interface DoctorForm {
  id?: number;
  doctorName: string;
  photo: string;
  hospitalArea: string;
  department: string;
  position: string;
  registrationFee: number;
  introduction: string;
  status: boolean;
}

// 路由与导航
const route = useRoute();
const router = useRouter();

// 表单数据
const formRef = ref(null);
const fileInput = ref<HTMLInputElement | null>(null);
const form = reactive<DoctorForm>({
  doctorName: '',
  photo: '',
  hospitalArea: '',
  department: '',
  position: '',
  registrationFee: 0,
  introduction: '',
  status: true
});

// 状态管理
const action = ref(route.query.action as string || 'add');
const actionText = computed(() => action.value === 'add' ? '新增医生' : '编辑医生');
const titleText = computed(() => action.value === 'add' ? '新增医生信息' : '编辑医生信息');
const tempPhoto = ref('');
const uploading = ref(false);
const uploadError = ref('');

// 表单验证规则
const rules = reactive({
  doctorName: [{ required: true, message: '请输入医生姓名', trigger: 'blur' }],
  photo: [{ required: true, message: '请上传医生照片', trigger: 'change' }],
  hospitalArea: [{ required: true, message: '请选择所属院区', trigger: 'change' }],
  department: [{ required: true, message: '请选择所属科室', trigger: 'change' }],
  position: [{ required: true, message: '请选择医生职称', trigger: 'change' }],
  registrationFee: [
    { type: 'number', message: '请输入有效的数字', trigger: 'blur' }
  ]
});

// 选项数据
const areaOptions = ref([
  { value: 'east', label: '东院' },
  { value: 'west', label: '西院' },
  { value:'south', label: '南院' },
  { value: 'north', label: '北院' },
  { value: 'central', label: '中心院区' }
]);

const departmentOptions = ref([
  { value: 'department1', label: '内科' },
  { value: 'department2', label: '外科' },
  { value: 'department3', label: '妇产科' },
  { value: 'department4', label: '儿科' },
  { value: 'department5', label: '急诊科' },
  { value: 'department6', label: '眼科' },
  { value: 'department7', label: '口腔科' }
]);

const positionOptions = ref([
  { value: '主任医师', label: '主任医师' },
  { value: '副主任医师', label: '副主任医师' },
  { value: '主治医师', label: '主治医师' },
  { value: '医师', label: '医师' },
  { value: '实习医师', label: '实习医师' }
]);

// 图片处理
const triggerUpload = () => {
  fileInput.value?.click();
};

const handleFileChange = (e: Event) => {
  const file = (e.target as HTMLInputElement).files?.[0];
  if (!file) return;
  if (!validateFile(file)) return;

  const reader = new FileReader();
  reader.onload = (event: any) => {
    tempPhoto.value = event.target.result;
    form.photo = event.target.result; // 保存Base64
  };
  reader.readAsDataURL(file);
};

const validateFile = (file: File): boolean => {
  const isJPG = file.type.match(/image\/(jpeg|png)/);
  if (!isJPG) {
    uploadError.value = '请上传JPG/PNG格式的图片';
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    uploadError.value = '图片大小不能超过2MB';
    return false;
  }
  uploadError.value = '';
  return true;
};

const clearPhoto = () => {
  tempPhoto.value = '';
  form.photo = '';
  fileInput.value = null;
};

// API 请求
const fetchDoctorDetail = async (id: number) => {
  try {
    const res = await fetchDoctorById(id);
    Object.assign(form, res);
    tempPhoto.value = form.photo;
  } catch (error) {
    console.log("获取医生信息失败")
  }
};

const saveDoctorData = async () => {
  try {
    const res = await saveDoctor(form);
    console.log(res)
    if(res.data.code==200){
        router.push('/home/doctor');
    }
  } catch (error) {
    console.error(error);
  }
};

// 表单操作
const handleSave = () => {
  (formRef.value as any).validate(async (valid: boolean) => {
    if (!valid) return;
    await saveDoctorData();
  });
};

const handleCancel = () => {
  router.go(-1);
};

// 生命周期钩子
onMounted(() => {
  if (action.value === 'edit' && route.query.id) {
    fetchDoctorDetail(Number(route.query.id));
  }
});

// 监听路由变化
watch(() => route.query, (query) => {
  action.value = query.action as string || 'add';
  if (action.value === 'edit' && query.id) {
    fetchDoctorDetail(Number(query.id));
  } else {
    // 重置表单
    form.doctorName = '';
    form.photo = '';
    form.hospitalArea = '';
    form.department = '';
    form.position = '';
    form.registrationFee = 0;
    form.introduction = '';
    form.status = true;
    tempPhoto.value = '';
  }
});
</script>

<style scoped>
.preview-container {
  margin-top: 10px;
}

.preview-image {
  position: relative;
  display: inline-block;
}

.preview-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #e5e7eb;
}

.delete-btn {
  position: absolute;
  top: 0;
  right: 0;
  transform: translate(25%, -25%);
}

.upload-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  border: 1px dashed #e5e7eb;
  border-radius: 4px;
  background-color: #f9fafb;
  color: #9ca3af;
  font-size: 12px;
}

.upload-error-message {
  color: #ef4444;
  font-size: 14px;
  margin-top: 5px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}
</style>